package com.molyfun.parents.utils;

import android.app.Activity;

import com.molyfun.parents.activity.MainActivity;
import com.molyfun.parents.activity.account.LoginActivity;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMManager;

import java.util.Iterator;
import java.util.Stack;

public class ActivityManager {

    private static ActivityManager mInstance;
    private Stack<Activity> mActivities = new Stack<Activity>();

    public static ActivityManager getInstance() {
        if (mInstance == null) {
            synchronized (ActivityManager.class) {
                if (mInstance == null)
                    mInstance = new ActivityManager();
            }
        }
        return mInstance;
    }

    public void logout() {
        Iterator<Activity> iterator = mActivities.iterator();
        while (iterator.hasNext()){
            Activity act = iterator.next();
            if(!(act instanceof LoginActivity)){
                try {
                    iterator.remove();
                    act.finish();
                } catch (Exception e) {

                }
            }
        }
        logoutTIM();
    }

    private void logoutTIM() {
        TIMManager.getInstance().logout(new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
            }

            @Override
            public void onSuccess() {
            }
        });
    }

    public void finishMainActivity(){
        Iterator<Activity> iterator = mActivities.iterator();
        while (iterator.hasNext()){
            Activity act = iterator.next();
            if(act instanceof MainActivity){
                try {
                    iterator.remove();
                    act.finish();
                } catch (Exception e) {

                }
            }
        }
    }

    public void close() {
        for (Activity act : mActivities) {
            try {
                act.finish();
            } catch (Exception e) {

            }
        }
        mActivities.clear();
    }

    public void addActivity(Activity act) {
        mActivities.add(act);
    }

    public void removeActivity(Activity act) {
        mActivities.remove(act);
    }


    public boolean isForeground(Activity act) {
        if (act != null && mActivities != null && mActivities.size() > 0
                && ((act.getClass().getSimpleName()).equals(mActivities.get(mActivities.size() - 1).getClass().getSimpleName()))) {
            return true;
        }
        return false;
    }
}
